import { ref } from 'vue'
import { useNotificationStore } from '../stores/notification.store'

class WebSocketService {
  private socket: WebSocket | null = null
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectTimeout = 3000
  private isConnecting = false
  private notificationStore = useNotificationStore()

  // 连接状态
  public connectionStatus = ref<'connected' | 'disconnected' | 'connecting'>('disconnected')

  // 建立WebSocket连接
  connect(userId: string) {
    if (this.isConnecting || this.socket?.readyState === WebSocket.OPEN) {
      return
    }

    this.isConnecting = true
    this.connectionStatus.value = 'connecting'

    try {
      this.socket = new WebSocket(`ws://localhost:8080/ws/notifications/${userId}`)

      this.socket.onopen = () => {
        this.connectionStatus.value = 'connected'
        this.isConnecting = false
        this.reconnectAttempts = 0
      }

      this.socket.onmessage = (event) => {
        const notification = JSON.parse(event.data)
        this.notificationStore.addNotification(notification)
      }

      this.socket.onclose = () => {
        this.connectionStatus.value = 'disconnected'
        this.isConnecting = false
        this.reconnect(userId)
      }

      this.socket.onerror = (error) => {
        console.error('WebSocket error:', error)
        this.connectionStatus.value = 'disconnected'
      }
    } catch (error) {
      console.error('Failed to establish WebSocket connection:', error)
      this.isConnecting = false
      this.reconnect(userId)
    }
  }

  // 重新连接
  private reconnect(userId: string) {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('Max reconnection attempts reached')
      return
    }

    this.reconnectAttempts++
    setTimeout(() => {
      this.connect(userId)
    }, this.reconnectTimeout)
  }

  // 关闭连接
  disconnect() {
    if (this.socket) {
      this.socket.close()
      this.socket = null
    }
  }
}

export const websocketService = new WebSocketService()